package com.ok.springbootupload.upload;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@RestController
public class FileController {

    private final static String filePath = "C:/";

    @PostMapping("/upload")
    public String fileUpload(@RequestParam("head_img")MultipartFile file, @RequestParam("name") String up,HttpServletRequest request){
        String name = request.getParameter("name");
        System.out.println("up:"+ up);
        System.out.println("request name:"+name);

        String fileName = file.getOriginalFilename();
        System.out.println("上传文件名为： "+ fileName);

        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("文件名后缀："+ suffixName);

        File dest = new File(filePath+fileName);


        //FileUploadBase$SizeLimitExceededException: 上传大小有限制
        // the request was rejected because its size (420333330) exceeds the configured maximum (10485760)
        // The field head_img exceeds its maximum permitted size of 1048576 bytes.

        /***
         * 源码中文件上传的, request最大是 10MB， MultipartFile file的大小是1MB
         *
         *     private DataSize maxFileSize = DataSize.ofMegabytes(1L);
         *     private DataSize maxRequestSize = DataSize.ofMegabytes(10L);
         *
         * 1. 可以通过application.properties解决
         * #上传文件大小限制
         * spring.servlet.multipart.max-file-size=20MB
         * spring.servlet.multipart.max-request-size=20MB
         *
         * 2. SpringBoot中更推荐添加配置类来设置
         *
         */
        try {
            OutputStream outputStream = new FileOutputStream(dest);
            //IOUtils.copy(file.getInputStream(), outputStream);
            // 大于1MB的文件，用copyLarge
            IOUtils.copyLarge(file.getInputStream(),outputStream);
            return "Success! "+ dest.getCanonicalPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // InputStream inputStream = new FileInputStream((File)file);


//        try {
//            file.transferTo(dest);
//            return "Success!"+ dest.getAbsolutePath();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return "fail";
    }
}
